package receptor;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Date;

public class AlertsProcessorServer extends Thread {
	
	private static final int PORT_LOW = 5190;
	
	protected DatagramSocket socket = null;
	protected BufferedReader in = null;
	protected boolean active = true;
	
	public AlertsProcessorServer(String name) throws SocketException{
		super(name);
		socket = new DatagramSocket(PORT_LOW);
	}
	
	public void run(){
		
		while(active){
			
			try {
				byte[] bufIn = new byte[256];
				byte[] bufOut = new byte[256];
				
				//Recibe el paquete
				DatagramPacket packet = new DatagramPacket(bufIn, bufIn.length);
				socket.receive(packet);
				
				System.out.println(bufIn.toString());
				
				String request = new String(bufIn);
				System.out.println(request);
				
				String response = "Paquete recibido -- " + new Date().toString();
				
				bufOut = response.getBytes();
				
				//Enviar la respuesta
				InetAddress address = packet.getAddress();
				int port = packet.getPort();
				packet = new DatagramPacket(bufOut, bufOut.length, address, port);
				socket.send(packet);
			} 
			catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
		
		socket.close();
	}
}
